import React, { ReactElement, useState } from 'react';
import { Text, View, ViewStyle } from 'react-native';

import MsgBox, { DirectType } from '../../../Graph/MsgBox';
import { Message } from '../../../../../../api/class/getMessageList';
import { phonePx } from '../../../../../../util/adapt';
import { CLASS_ROOM_RIGHT_SCALE } from '../../../../constant';
import styles from './style';
import {
  MAX_TEXT_MESSAGE_WIDTH,
  MIN_TEXT_MESSAGE_HEIGHT
} from '../../constant';

export enum TextMessageType {
  Unknown,
  Bubble,
  Own,
  Other
}

export enum VoiceType {
  Unknown,
  First,
  Second,
  Third
}

interface PlayVoiceProps {
  textMessageType: TextMessageType;
  message: Message;
  style?: ViewStyle | ViewStyle[];
  maxWidth?: number;
  minHeight?: number;
  numberOfLines?: number;
}

export default ({
  style,
  textMessageType,
  message,
  maxWidth = MAX_TEXT_MESSAGE_WIDTH,
  minHeight = MIN_TEXT_MESSAGE_HEIGHT,
  numberOfLines
}: PlayVoiceProps): ReactElement => {
  const [width, setWidth] = useState<number>(0);
  const [height, setHeight] = useState<number>(0);
  const { textMessage } = message;
  const { text } = textMessage;

  let fillColor = 'rgba(243, 243, 243, 1)';
  if (textMessageType === TextMessageType.Own) {
    fillColor = 'rgba(247, 215, 106, 1)';
  } else if (textMessageType === TextMessageType.Other) {
    fillColor = 'rgba(246, 246, 246, 1)';
  }

  let directType = DirectType.Bottom;
  if (textMessageType === TextMessageType.Own) {
    directType = DirectType.Right;
  } else if (textMessageType === TextMessageType.Other) {
    directType = DirectType.Left;
  }

  return (
    <View style={style}>
      {width > 0 && height > 0 && (
        <MsgBox
          style={styles.box}
          fillColor={fillColor}
          directType={directType}
          dia={phonePx(4) * CLASS_ROOM_RIGHT_SCALE}
          surfaceWidth={width}
          surfaceHeight={height}
          directLocation={
            directType === DirectType.Left || directType === DirectType.Right
              ? phonePx(11) * CLASS_ROOM_RIGHT_SCALE
              : 0
          }
        />
      )}
      <View
        style={[
          styles.content,
          { minHeight, maxWidth },
          directType === DirectType.Bottom
            ? { marginBottom: phonePx(5) * CLASS_ROOM_RIGHT_SCALE }
            : {},
          directType === DirectType.Left
            ? { marginLeft: phonePx(5) * CLASS_ROOM_RIGHT_SCALE }
            : {},
          directType === DirectType.Right
            ? { marginRight: phonePx(5) * CLASS_ROOM_RIGHT_SCALE }
            : {}
        ]}
        onLayout={(e): void => {
          const { width: w, height: h } = e.nativeEvent.layout;
          setWidth(Math.round(w));
          setHeight(Math.round(h));
        }}
      >
        <Text style={styles.value} numberOfLines={numberOfLines}>
          {text}
        </Text>
      </View>
    </View>
  );
};
